﻿using System;
using System.Drawing;
using System.Net;
using System.Windows.Forms;
using System.Threading;

namespace ScreenTcpServer
{
    //主窗口类
    public partial class MainForm : Form
    {
        //服务器
        public TcpServer TcpServer;
        //监听端口
        public int Port = 51234;


        //构造方法
        public MainForm()
        {
            //初始化组件
            InitializeComponent();
            //本机IP
            IPLabel.Text = $"本机IP：{IPHelper.GetLocalIPs()}";
            //创建服务器
            TcpServer = new TcpServer(IPAddress.Any, Port);
            //启动定时器1
            Timer1.Start();
        }


        //启动服务器按钮单击事件
        private void Button1_Click(object sender, EventArgs e)
        {
            //禁用按钮
            Button1.Enabled = false;
            //启动服务器
            new Thread(StartServer).Start();
        }

        //启动服务器
        private void StartServer()
        {
            TcpServer?.Start();
        }

        //停止服务器按钮单击事件
        private void Button2_Click(object sender, EventArgs e)
        {
            TcpServer?.Stop();
            //启用按钮
            Button1.Enabled = true;
        }

        //定时器1触发事件
        private void Timer1_Tick(object sender, EventArgs e)
        {
            if (TcpServer.IsRunning)
            {
                Label1.Text = $"服务器已启动，客户端请用浏览器访问 http://服务器ip:{Port}";
                Label1.ForeColor = Color.Green;
            }
            else
            {
                Label1.Text = $"服务器未启动，客户端请用浏览器访问 http://服务器ip:{Port}";
                Label1.ForeColor = Color.Red;
            }

            Label2.Text = $"客户端计数： {TcpServer.ClientCount}";
            TimeLabel.Text = $"服务器时间： {DateTime.Now}";
        }


        //窗口关闭事件
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Timer1.Stop();
            TcpServer?.Stop();
            Environment.Exit(0);
        }


    }
}
